//
//  DDRegisterViewController.m
//  DingDongZP
//
//  Created by Jyh on 16/3/13.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

#import "DDRegisterViewController.h"
#import "AppDelegate.h"
#import "DDRegisterAgreementViewController.h"

#import "DDRegisterSerivce.h"
#import "DDGetVerifyCodeService.h"
#import "DDChoosePositonViewController.h"

@interface DDRegisterViewController () <UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIView         *accountView;
@property (weak, nonatomic) IBOutlet UIView         *passwordView;
@property (weak, nonatomic) IBOutlet UIView         *codeView;

@property (weak, nonatomic) IBOutlet UIButton       *passwordButton;
@property (weak, nonatomic) IBOutlet UIButton       *getCodeButton;
@property (weak, nonatomic) IBOutlet UIButton       *registerButton;

@property (weak, nonatomic) IBOutlet UITextField    *accountTF;
@property (weak, nonatomic) IBOutlet UITextField    *passwordTF;
@property (weak, nonatomic) IBOutlet UITextField    *codeTF;

@property (nonatomic) NSTimer *timer;
@property (nonatomic) int countDownTime;
@property (nonatomic)BOOL timeBool;//重新发送后时间到了才允许再次获取

@property (strong, nonatomic) DDRegisterSerivce *registerService;
@property (strong, nonatomic) DDGetVerifyCodeService *getVerifyCodeService;

- (IBAction)onShowOrHidePswClick:(id)sender;
- (IBAction)onGetCodeButtonClick:(id)sender;
- (IBAction)onRegisterButtonClick:(id)sender;
- (IBAction)onAgreementButtonClick:(id)sender;

@end

@implementation DDRegisterViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.registerService = [[DDRegisterSerivce alloc] init];
        self.getVerifyCodeService = [[DDGetVerifyCodeService alloc] init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.accountView.layer.cornerRadius = 5.f;
    self.accountView.layer.masksToBounds = YES;
    self.passwordView.layer.cornerRadius = 5.f;
    self.passwordView.layer.masksToBounds = YES;
    self.codeView.layer.cornerRadius = 5.f;
    self.codeView.layer.masksToBounds = YES;
    
    [self setRegisterNavgationBar];
    
    self.countDownTime = 60;
}

- (void)setRegisterNavgationBar
{
    self.navigationController.navigationBar.translucent = NO;
    
    if ([self.navigationController.navigationBar respondsToSelector:@selector( setBackgroundImage:forBarMetrics:)]){
        NSArray *list = self.navigationController.navigationBar.subviews;
        for (id obj in list) {
            if ([obj isKindOfClass:[UIImageView class]]) {
                UIImageView *imageView = (UIImageView *)obj;
                NSArray *list2 = imageView.subviews;
                for (id obj2 in list2) {
                    if ([obj2 isKindOfClass:[UIImageView class]]) {
                        UIImageView *imageView2 = (UIImageView *)obj2;
                        imageView2.hidden = YES;
                    }
                }
            }
        }
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
}

#pragma mark
#pragma mark - Action

- (BOOL)validatePhoneNumber:(NSString *)string
{
    if (string.length != 11) {
        return NO;
    }
    return YES;
}

- (BOOL)validatePassword:(NSString *)password
{
    if (password.length < 6 || password.length > 25) {
        return NO;
    }
    return YES;
}

#pragma mark
#pragma mark - 倒计时

//倒计时操作
- (void)countDown
{
    self.countDownTime --;
    if (self.countDownTime == 0)
    {
        if ([self.timer isValid]) {

            [self.timer invalidate];
            [self changeButtonState];
            return;
        }
    }
    
    [self.getCodeButton setTitle:[NSString stringWithFormat:@"已发送(%d)",self.countDownTime] forState:UIControlStateNormal];
    [self.getCodeButton setUserInteractionEnabled:NO];
}

- (void)changeButtonState
{
    [self.getCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.getCodeButton setUserInteractionEnabled:YES];
}

- (void)stopTimer {
    if (nil != self.timer && [self.timer isValid]) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

#pragma mark
#pragma mark - IBAction

- (IBAction)onShowOrHidePswClick:(id)sender {
    UIButton *button = (UIButton *)sender;
    
    button.selected = !button.selected;
        
    // 解决密码框secureTextEntry属性切换时候，光标不准的bug。
    NSString *tempString = self.passwordTF.text;
    self.passwordTF.text = @"";
    self.passwordTF.secureTextEntry = !button.selected;
    self.passwordTF.text = tempString;
}

- (IBAction)onGetCodeButtonClick:(id)sender {

    if (![self validatePhoneNumber:self.accountTF.text]) {
        [self showText:@"手机号码格式有误"];
        return;
    }
    [self showLoading];
    WEAKSELF
    [self.getVerifyCodeService queryRegisterWithMobile:self.accountTF.text successBlock:^(id responseObject) {
        [weakSelf hideLoading];
        if ([weakSelf isValidateResponseData:responseObject]) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf showText:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
            });
            
            weakSelf.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:weakSelf selector:@selector(countDown) userInfo:nil repeats:YES];
            weakSelf.countDownTime = 60;
        } else {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf showText:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
            });
        }
        
    } failBlock:^(id responseObject, NSError *error) {
        [weakSelf requestFaild];
    }];
}

- (IBAction)onRegisterButtonClick:(id)sender {
    
    if (![self validatePhoneNumber:self.accountTF.text]) {
        [self showText:@"手机号码格式有误"];
        return;
    }
    if (![self validatePassword:self.passwordTF.text]) {
        [self showText:@"密码格式有误"];
        return;
    }
    if (self.codeTF.text.length < 1) {
        [self showText:@"验证码格式有误"];
        return;
    }
    
    [self showLoading];
    
    
    WEAKSELF
//    [self.registerService queryRegisterWithMobile:self.accountTF.text password:self.passwordTF.text code:self.codeTF.text successBlock:^(id responseObject) {
//        if ([weakSelf isValidateResponseData:responseObject]) {
//            
//            
//            // 登录成功
//            [DDLoginUserManager setAccount:weakSelf.accountTF.text];
//            // 保存token
//            [DDLoginUserManager setToken:responseObject[@"data"]];
//            
//            [weakSelf showSuccessWithText:@"注册成功!"];
//            
//            [weakSelf registerSuccess];
//        } else {
//            
//            [weakSelf responseUnValidate:responseObject];
//        }
//        
//    }
//     
//        failBlock:^(id responseObject, NSError *error) {
//        [weakSelf requestFaild];
//    }];
    
    if (self.registerService ) {
        [self.registerService queryRegisterWithMobile:self.accountTF.text password:self.passwordTF.text code:self.codeTF.text successBlock:^(id responseObject) {
            
            if ([[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"code"]]isEqualToString:@"1"]) {
                
                [weakSelf hideLoading];
                [weakSelf showText:[responseObject objectForKey:@"msg"]];
                DDLoginViewController *vc = [[DDLoginViewController alloc]init];
                [self.navigationController pushViewController:vc animated:YES];
                
                
            }else{
                
                [weakSelf hideLoading];
                [weakSelf showText:[responseObject objectForKey:@"msg"]];
                
            }
            
        } failBlock:^(id responseObject, NSError *error) {
            
                [weakSelf registerSuccess];
            
        }];
    }
    
}

- (void)registerSuccess
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        DDChoosePositonViewController *agreement = [[DDChoosePositonViewController alloc] init];
        //注册成功后执行用户信息的操作
        [self.navigationController pushViewController:agreement animated:YES];
    });
}

- (IBAction)onAgreementButtonClick:(id)sender {
    DDRegisterAgreementViewController *agreement = [[DDRegisterAgreementViewController alloc] init];
    
    [self.navigationController pushViewController:agreement animated:YES];
}

#pragma mark
#pragma mark - UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (self.view.bounds.origin.y > 190) {
        return;
    }
     CGRect newbounds = self.view.bounds;
    newbounds.origin.y +=190;

    [UIView animateWithDuration:.3f animations:^{
        self.view.bounds = newbounds;
    }];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (self.view.bounds.origin.y == 190) {
        CGRect newbounds = self.view.bounds;
        newbounds.origin.y = 0;
        
        [UIView animateWithDuration:.3f animations:^{
            self.view.bounds = newbounds;
        }];
    }
}

@end
